<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="轮播图名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入轮播图名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:banner:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:banner:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:banner:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="bannerList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="轮播图名称" align="center" prop="name" />
      <el-table-column label="轮播图信息" align="center" prop="description" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:banner:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:banner:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改banner管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="轮播图名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入轮播图名称" />
        </el-form-item>
        <el-form-item label="轮播图信息" prop="description">
          <el-input v-model="form.description" placeholder="请输入轮播图信息" />
        </el-form-item>
        <el-divider content-position="center">轮播图单项信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddBannerItem"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteBannerItem"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="bannerItemList"
          :row-class-name="rowBannerItemIndex"
          @selection-change="handleBannerItemSelectionChange"
          ref="bannerItem"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column label="轮播图图片(600*400)" prop="imgUrl">
            <template slot-scope="scope">
              <el-upload
                action="/prod-api/file/upload"
                class="avatar-uploader"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="{ Authorization: getToken() }"
              >
                <img
                  v-if="scope.row.imgUrl"
                  :src="scope.row.imgUrl"
                  @click="imageClick(scope.$index)"
                  class="avatar"
                />
                <i
                  v-else
                  @click="imageClick(scope.$index)"
                  class="el-icon-plus avatar-uploader-icon"
                ></i>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column
            label="对应的文章编号/标题"
            prop="announcementId"
            width="250"
          >
            <template slot-scope="scope">
              <el-select
                filterable
                remote
                v-model="scope.row.announcementId"
                @click.native="remoteMethod"
                v-scroll="handleScroll"
                ref="select"
                max-height="300px"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBanner,
  getBanner,
  delBanner,
  addBanner,
  updateBanner,
} from "@/api/system/banner";
import { getToken } from "@/utils/auth";
import { listAnnouncement } from "@/api/system/announcement";

export default {
  name: "Banner",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBannerItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // banner管理表格数据
      bannerList: [],
      // banner子项表格数据
      bannerItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        description: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "轮播图名称不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "轮播图名称长度不能超过50个字符", trigger: "blur" }
        ],
        description: [
          { required: true, message: "轮播图信息不能为空", trigger: "blur" },
          { min: 1, max: 200, message: "轮播图信息长度不能超过200个字符", trigger: "blur" }
        ]
      },
      clickIndex: -1,
      // 公告
      announcementParams: {
        current: 1,
        size: 10,
      },
      options: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    remoteMethod() {
      this.options = [];
      this.announcementParams.current = 1;
      this.getAnnouncement();
    },
    getAnnouncement() {
      listAnnouncement(this.announcementParams).then((response) => {
        this.options = this.options.concat(
          response.data.records.map((item) => ({
            label: item.title,
            value: item.id + "",
          }))
        );
        this.announcementParams.current += 1;
      });
    },
    handleScroll() {
      this.getAnnouncement();
    },
    // 点击上传图片的回调，记录index，以便将上传后的图片准确记录下来
    imageClick(index) {
      console.log(index);
      this.clickIndex = index;
    },
    getToken() {
      return getToken();
    },
    handleAvatarSuccess(res, file) {
      this.bannerItemList[this.clickIndex].imgUrl = res.data.url;
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("只能上传图片！");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
      }
      return isImage && isLt2M;
    },
    /** 查询banner管理列表 */
    getList() {
      this.loading = true;
      listBanner(this.queryParams).then((response) => {
        this.bannerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        description: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
      };
      this.bannerItemList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加轮播图";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBanner(id).then((response) => {
        this.form = response.data;
        this.bannerItemList = response.data.bannerItemList;
        this.open = true;
        this.title = "修改轮播图";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.name = this.form.name.trim();
          this.form.description = this.form.description.trim();
          if (this.form.name.length > 50){
            this.$modal.msgError("名称不能超过50个字符");
            return;
          }
          if (this.form.description.length > 200){
            this.$modal.msgError("描述不能超过200个字符");
            return;
          }
          this.form.bannerItemList = this.bannerItemList;
          if (this.form.id != null) {
            updateBanner(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBanner(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除选中的轮播图？")
        .then(function () {
          return delBanner(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** banner子项序号 */
    rowBannerItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** banner子项添加按钮操作 */
    handleAddBannerItem() {
      let obj = {};
      obj.imgUrl = "";
      obj.announcementId = "";
      this.bannerItemList.push(obj);
    },
    /** banner子项删除按钮操作 */
    handleDeleteBannerItem() {
      if (this.checkedBannerItem.length == 0) {
        this.$modal.msgError("请先选择要删除的banner子项数据");
      } else {
        const bannerItemList = this.bannerItemList;
        const checkedBannerItem = this.checkedBannerItem;
        this.bannerItemList = bannerItemList.filter(function (item) {
          return checkedBannerItem.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleBannerItemSelectionChange(selection) {
      this.checkedBannerItem = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/banner/export",
        {
          ...this.queryParams,
        },
        `banner_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.avatar {
  width: 300px;
  height: 200px;
  display: block;
}
</style>
